import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useGlobalStore } from '@/store/global'
import { getUrlParams } from '@/utils'
import jumpPage from '@/utils/jumpPage'
import { ColumnProps, Modal } from '@kedacom/react-next'
import { ITemplateTableData } from './interface'
import { useRequest } from 'ahooks'
import { fetchDeletePersonalTemplates, fetchGetPersonalTemplates } from '@/api/template'
import { transPersonalTemplate } from './translate'
import { fetchStatus } from '@/api/global'
import Alert, { confirmModal } from '@/components/Alert'
import { IPersonalTemplate } from '@/api/template/interface'
import { t } from 'i18next'

const pageSize = 20
const curPageNo = getUrlParams('curPageNo') ? Number(getUrlParams('curPageNo')) : 1

export default function useTemplateService() {
	const user = useGlobalStore((state) => state.user)
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	/*
	templatesData
	转换前table的数据 
	*/
	const templatesData = useRef<IPersonalTemplate[]>([])
	/*

	templateData
	点击立即召开按钮出现的弹窗 --- 里面的数据
	
	<MeetingConveneModal data={templateData} open={isShowModal} setOpen={setIsShowModal} />

	*/
	const templateData = useRef<IPersonalTemplate | null>(null)
	/*
	data table的数据
	*/
	const [data, setData] = useState<ITemplateTableData[]>([])
	/*
	selectedRowIds 选中的数据
	*/
	const [selectedRowIds, setSelectedRowIds] = useState<string[]>([])
	const [isShowModal, setIsShowModal] = useState<boolean>(false)
	/*
	分页组件的数据
	*/
	const [pager, setPager] = useState({ page: curPageNo, size: pageSize, total: 1 })
	/*
	isShowConveneBtn  是否展示立即召开按钮
	
	useMemo 计算属性 当user改变，才会重新计算

	*/
	const isShowConveneBtn = useMemo(() => !!(!user?.cms_virtual_approval || user?.enable_cms_approval), [user])
	/*
	table的columns
	*/
	const columns: ColumnProps<ITemplateTableData>[] = [
		{ title: t('名称'), dataKey: 'templateName' },
		{
			title: t('会议规模', { context: 'SC1' }),
			dataKey: 'templateScale',
			width: SWITCH.template.tableWidth[0],
		},
		{ title: t('与会方'), dataKey: 'mtNum', width: SWITCH.template.tableWidth[1] },
		{ title: t('媒体能力'), dataKey: 'rate', width: SWITCH.template.tableWidth[2] },
		!!SWITCH.showMeetingType && { title: t('会议类型'), dataKey: 'type', width: SWITCH.template.tableWidth[3] },
		{ title: t('会议号码'), dataKey: 'e164', width: SWITCH.template.tableWidth[4] },
		{ title: t('会议不可见'), dataKey: 'security', width: SWITCH.template.tableWidth[5] },
		{ title: t('数据加密'), dataKey: 'encryptedType', width: SWITCH.template.tableWidth[6] },
	].filter(Boolean) as ColumnProps<ITemplateTableData>[]

	/*
	run 接口请求--获取个人会议模板列表

	1.templatesData 设置table的数据
	1.setData   转换后table的数据
	2.setPager  更新分页组件的数据
	3.setSelectedRowIds 清空选中的数据
	*/
	const { run } = useRequest(
		(pageIndex) => fetchGetPersonalTemplates({ order: 1, count: pager.size, start: pager.size * (pageIndex - 1) }),
		{
			manual: true,
			onSuccess(res, [pageIndex]) {
				if (res) {
					let total = res.total
					templatesData.current = res.data
					setData(transPersonalTemplate(res.data))
					let maxPageNum = total === 0 ? 1 : Math.ceil(total / pager.size)
					if (maxPageNum < pageIndex) {
						setPager({ ...pager, page: maxPageNum, total })
						run(maxPageNum)
					} else {
						setPager({ ...pager, page: pageIndex, total })
					}
					setSelectedRowIds([])
				}
			},
		}
	)

	/*
	run 接口请求--获取个人会议模板列表  默认获得第一页的数据
	*/
	useEffect(() => {
		run(1)
	}, [])

	/*
	handlePageChange  页码改变时

	1.run 接口请求--获取个人会议模板列表  
	
	*/
	const handlePageChange = (pageIndex: number) => {
		run(pageIndex)
	}
	/*
	handleConveneMt 点击立即召开
	*/
	const handleConveneMt = () => {
		let data = templatesData.current.find((i) => i.template_id === selectedRowIds[0])
		if (!data) return
		templateData.current = data
		setIsShowModal(true)
	}
	/*
	handleEdit 点击修改按钮 跳转页面
	*/
	const handleEdit = () => {
		fetchStatus(() => {
			window.location.href = './edit.html?templateMoid=' + selectedRowIds[0]
		})
	}

	/*
	handleDelete 点击删除按钮

	1.fetchStatus 机房是否托管状态
	2.fetchDeletePersonalTemplates  删除个人会议模板
	3.
	*/
	const handleDelete = () => {
		fetchStatus(() => {
			confirmModal({
				msg: <div>{t('您确定要删除选择的模板吗？')}</div>,
				onOk: () => {
					fetchDeletePersonalTemplates(selectedRowIds).then((res) => {
						if (res.success) {
							if (data.length <= selectedRowIds.length) {
								run(Math.max(pager.page - 1, 1))
							} else {
								run(pager.page)
							}
						} else {
							Alert(t('操作失败！'))
						}
					})
				},
			})
		})
	}
	/*
	handleAdd 点击添加按钮

	1.fetchStatus 接口请求--机房是否托管状态
	2.jumpPage 跳转页面
	*/
	const handleAdd = () => {
		fetchStatus(() => {
			jumpPage('edit')
		})
	}
	return {
		columns,
		data,
		pager,
		selectedRowIds,
		isShowConveneBtn,
		isShowModal,
		templateData: templateData.current,
		setIsShowModal,
		setSelectedRowIds,
		handlePageChange,
		handleConveneMt,
		handleEdit,
		handleDelete,
		handleAdd,
	}
}
